package com.study.util.treeutil;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 树构建1.0
 * 
 * @author chenk
 *
 */
public class TreeUtil {

	/**
	 * 树构建
	 * 
	 * @param menuEntityList
	 * @param parentId
	 * @return
	 */
	public static List<TreeNode> build(List<TreeNode> treeNodes, Object parentId) {

		List<TreeNode> finalTreeNodes = new ArrayList<>();
		for (TreeNode treeNode : treeNodes) {
			if (parentId.equals(treeNode.getParentId())) {
				finalTreeNodes.add(treeNode);
				innerBuild(treeNodes, treeNode);
			}
		}

		return finalTreeNodes;

	}

	private static void innerBuild(List<TreeNode> treeNodes, TreeNode parentNode) {
		for (TreeNode childNode : treeNodes) {
			if (parentNode.getId().equals(childNode.getParentId())) {
				List<TreeNode> children = parentNode.getChildren();
				if (children == null) {
					children = new ArrayList<>();
					parentNode.setChildren(children);
				}
				children.add(childNode);
				childNode.setParentId(parentNode.getId());
				innerBuild(treeNodes, childNode);
			}
		}
	}

	public static void main(String[] args) throws JsonProcessingException {
		// 1.模拟菜单数据
		List<MenuEntity> list = new ArrayList<>();
		list.add(new MenuEntity("1", "0", "系统管理", "sys", "/sys"));
		list.add(new MenuEntity("11", "1", "用户管理", "user", "/sys/user"));
		list.add(new MenuEntity("111", "11", "用户添加", "userAdd", "/sys/user/add"));
		list.add(new MenuEntity("2", "0", "店铺管理", "store", "/store"));
		list.add(new MenuEntity("21", "2", "商品管理", "shop", "/shop"));

		// 2.MenuEntity->TreeNode
		List<TreeNode> treeNodes = new ArrayList<>();
		for (MenuEntity menuEntity : list) {
			TreeNode treeNode = new TreeNode();
			treeNode.setId(menuEntity.getId());
			treeNode.setParentId(menuEntity.getPid());
			treeNode.setCode(menuEntity.getCode());
			treeNode.setName(menuEntity.getName());
			treeNode.setLinkUrl(menuEntity.getUrl());
			treeNodes.add(treeNode);
		}

		// 3.树构建
		List<TreeNode> build = TreeUtil.build(treeNodes, "0");
		ObjectMapper om = new ObjectMapper();
		String result = om.writeValueAsString(build);
		System.out.println(result);
	}
}
